package cn.bugstack.mybatis.transaction.jdbc;

import java.sql.Connection;
import java.sql.SQLException;

import javax.sql.DataSource;

import cn.bugstack.mybatis.session.TransactionIsolationLevel;
import cn.bugstack.mybatis.transaction.Transaction;

/**
 * description: jdbc事物类
 * taskId：
 * <pre>
 * change history:
 * date             defect#             person                comments
 * ---------------------------------------------------------------------
 * 2024/11/27       ********         zhaochaoyue        create file
 * </pre>
 *
 * @author: zhaochaoyue
 * @date: 2024/11/27 15:07
 * @copyright: 2024
 */
public class JdbcTransaction implements Transaction {
    
    protected Connection connection;
    
    protected DataSource dataSource;
    
    protected TransactionIsolationLevel level = TransactionIsolationLevel.NONE;
    
    protected boolean autoCommit;

    public JdbcTransaction(Connection connection) {
        this.connection = connection;
    }

    public JdbcTransaction(DataSource dataSource, TransactionIsolationLevel level, boolean autoCommit) {
        this.dataSource = dataSource;
        this.level = level;
        this.autoCommit = autoCommit;
    }

    @Override
    public Connection getConnection() throws SQLException {
        connection = dataSource.getConnection();
        connection.setTransactionIsolation(level.getLevel());
        connection.setAutoCommit(autoCommit);
        return connection;
    }

    @Override
    public void commit() throws SQLException {
        if(connection !=null && !connection.getAutoCommit()){
            connection.commit();
        }
    }

    @Override
    public void rollback() throws SQLException {
        if(connection !=null && !connection.getAutoCommit()){
            connection.rollback();
        }
    }

    @Override
    public void close() throws SQLException {
        if(connection !=null && !connection.getAutoCommit()){
            connection.close();
        }
    }
}
